package com.nowcoder.community.controller;

import com.nowcoder.community.service.AlphaService;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("/alpha")
public class AlphaController {

    @Autowired
    private AlphaService alphaService;

    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello() {
        return "Hello Spring Boot.";
    }

    @RequestMapping("/data")
    @ResponseBody
    public String getData() {
        return alphaService.find();
    }

    @RequestMapping("/http")
    // 直接用response就能返回对象，不依赖函数的返回值，所以用void
    // URL输入示例 http://localhost:8080/community/alpha/http?code=123
    public void http(HttpServletRequest request, HttpServletResponse response) {
        // 获取请求数据
        System.out.println(request.getMethod());   // 请求方法
        System.out.println(request.getServletPath());  // 请求路径，这两个是第一行的数据
        Enumeration<String> enumeration = request.getHeaderNames(); // 这个是消息头
        while(enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            System.out.println(name + ":" + value);
        }
        System.out.println(request.getParameter("code")); // 这个是传入的参数

        // 返回响应数据
        response.setContentType("text/html;charset=utf-8");  // 支持中文
        try(PrintWriter writer = response.getWriter();)
        {
            writer.write("</hl>牛客网</hl>"); // 通过write向网页响应
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // GET请求
//更简洁的处理办法
    //GET请求怎么处理（默认的请求是get）
    //eg:查询所有学生: /students?current=1&limit=20
    @RequestMapping(path = "/students", method = RequestMethod.GET) // 必须get请求才能处理
    @ResponseBody
    public String getStudents(
            // @RequestParam 用来处理/students，即没有传入current和limit参数
            @RequestParam(name = "current",required = false,defaultValue = "1") int current,
            @RequestParam(name = "limit",required = false,defaultValue = "10") int limit
    ){
        System.out.println(current);
        System.out.println(limit);
        return "some students";
    }

    //查询一个学生，根据学生的id:/student/123:参数是路径的一部分
    @RequestMapping(path = "/student/{id}",method = RequestMethod.GET)
    @ResponseBody
    // @PathVariable 注解用来从路径中得到id变量赋值给函数中的形参id
    public String getStudent(@PathVariable("id") int id) {
        System.out.println(id);
        return "a student";
    }

    //post请求获取参数
    @RequestMapping(path = "/student",method = RequestMethod.POST)
    @ResponseBody
    public String saveStudent(String name,int age){
        System.out.println(name);
        System.out.println(age);
        return "success";
    }

    //响应html数据，以网页形式响应
    //此时就不需要加 @ResponseBody，默认返回html
    @RequestMapping(path = "/teacher",method = RequestMethod.GET)
    // 不加@ResponseBody默认返回的是html
    public ModelAndView getTeacher(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("name","张三");
        modelAndView.addObject("age",30);
        //看模板需要多少对象
        //设置模板的名字和路径
        modelAndView.setViewName("/demo/view");//不用写成view.html，即不用写后缀
        return modelAndView;//返回对象
    }

    @RequestMapping(path = "/school",method = RequestMethod.GET)
    public String getSchool(Model model){
        //这个model是dispatchservlet调方法时，实例化后传过来的
        model.addAttribute("name","北京大学");
        model.addAttribute("age","years");
        return "/demo/view";//若返回的是String,则返回模板的路径
    }

    //向浏览器响应JSON数据，异步请求中：当前网页不刷新，但又访问了服务器，局部验证(是否，成功失败)
    //Java对象，--> json字符串(一种数据格式) --> JS对象，通过JSON实现两者的兼容，
    @RequestMapping(path = "/emp",method = RequestMethod.GET)
    @ResponseBody//要返回JSON数据，要加此说明，不然默认会返回html
    public Map<String,Object> getEmp(){
        Map<String,Object> emp=new HashMap<>();
        emp.put("name","张三");
        emp.put("age",23);
        emp.put("salary",8000);
        return emp;
    }
    //返回一组员工
    @RequestMapping(path = "/emps",method = RequestMethod.GET)
    @ResponseBody//要返回JSON数据，要加此说明，不然默认会返回html
    public List<Map<String,Object>> getEmps(){
        List<Map<String,Object>> list=new ArrayList<>();
        Map<String,Object> emp=new HashMap<>();
        emp.put("name","张三");
        emp.put("age",23);
        emp.put("salary",8000);
        list.add(emp);
        emp=new HashMap<>();
        emp.put("name","李四");
        emp.put("age",25);
        emp.put("salary",7000);
        list.add(emp);

        emp=new HashMap<>();
        emp.put("name","王五");
        emp.put("age",28);
        emp.put("salary",4000);
        list.add(emp);
        return list;
    }

    //cookie示例
    @RequestMapping(path = "/cookie/set",method = RequestMethod.GET)
    @ResponseBody
    public String setCookie(HttpServletResponse response){
        //创建cookie，必须传入参数，没有无参构造器，都是String,并且只能传一对key Value.
        Cookie cookie=new Cookie("code", CommunityUtil.generateUUID());
        //设置cookie生效范围
        cookie.setPath("/community/alpha");
        //设置cookie生存时间,单位是s
        cookie.setMaxAge(60 * 10);
        //发送cookie
        response.addCookie(cookie);

        return "set cookies";
    }

    @RequestMapping(path = "/cookie/get",method = RequestMethod.GET)
    @ResponseBody
    public String getCookie(@CookieValue("code") String code){
        return code;
    }

    //session
    @RequestMapping(path = "/session/set",method = RequestMethod.GET)
    @ResponseBody
    public String setSession(HttpSession session){
        session.setAttribute("id",1);
        session.setAttribute("name","Test");
        return "Set session";
    }

    @RequestMapping(path = "/session/get",method = RequestMethod.GET)
    @ResponseBody
    public String getSession(HttpSession session){
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("name"));
        return "get session";
    }

    // ajax示例
    @RequestMapping(path = "/ajax", method = RequestMethod.POST)
    @ResponseBody
    public String testAjax(String name, int age) {
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0, "操作成功");
    }



}
